package stack.medium;


import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class NumberOfElements {
    public String get(String str){
        Stack<String> strStack = new Stack<>();
        Stack<Integer> intStack = new Stack<>();
        int multi = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == '(') {
                strStack.push(String.valueOf(c));
            } else if (c == ')') {
                int j = i + 1;
                while (j < str.length()) {
                    char tmp = str.charAt(j);
                    if(!Character.isDigit(tmp)) {
                        break;
                    }
                    multi = multi * 10 + (tmp - '0');
                    j++;
                }
                i = j - 1;
                multi = multi == 0 ? 1 : multi;
                Stack<String> strQueue = new Stack<>();
                Stack<Integer> intQueue = new Stack<>();

                while (!strStack.peek().equals("(")) {
                    String s = strStack.pop();
                    Integer num = intStack.pop() * multi;
                    strQueue.push(s);
                    intQueue.push(num);
                }
                strStack.pop();
                while (!strQueue.isEmpty()) {
                    strStack.push(strQueue.pop());
                    intStack.push(intQueue.pop());
                }
                multi = 0;
            } else if (Character.isLetter(c)) {
                StringBuilder sb = new StringBuilder();
                sb.append(c);
                int j = i + 1;
                while (j < str.length()){
                    char tmp = str.charAt(j);
                    if (!Character.isLowerCase(tmp)) {
                        break;
                    }
                    sb.append(tmp);
                    j++;
                }
                while (j < str.length()) {
                    char tmp = str.charAt(j);
                    if (!Character.isDigit(tmp)){
                        break;
                    }
                    multi = multi * 10 + (tmp - '0');
                    j++;
                }
                i = j - 1;
                strStack.push(sb.toString());
                intStack.push(multi == 0 ? 1 : multi);
                multi = 0;
            }
        }
        StringBuilder sb = new StringBuilder();
        while (!strStack.isEmpty()) {
            String res = strStack.pop() + intStack.pop();
            sb.insert(0, res);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        NumberOfElements bc = new NumberOfElements();
        System.out.println(bc.get("Fe(SO4)3"));
    }
}
